package logic
{
import mx.collections.XMLListCollection;
import mx.events.FlexEvent;

import view.ElementIcon;
import view.LineIcon;
	
public class SBVAEditorLogic extends Logic
{
	public function SBVAEditorLogic()
	{
		super();
	}

	// 初期化処理
    override protected function onCreationCompleteHandler(event:FlexEvent):void {
    	trace(this + "onCreationCompleteHandler(event=" + event + ")");
/*
        var ei1:ElementIcon = new ElementIcon();
        //ei1.model = new XML("<Subject x=\"200\" y=\"200\">患者</Subject>");
        ei1.model = new XML("<Subject>患者</Subject>");
        this.sbvaEditor.birdsEyeView.addChild(ei1);

        var ei2:ElementIcon = new ElementIcon();
        ei2.model = new XML("<Verb>提出する</Verb>");
        this.sbvaEditor.birdsEyeView.addChild(ei2);

        var ei3:ElementIcon = new ElementIcon();
        ei3.model = new XML("<Object>診察券</Object>");
        this.sbvaEditor.birdsEyeView.addChild(ei3);

        var ei4:ElementIcon = new ElementIcon();
        ei4.model = new XML("<Object>保険証</Object>");
        this.sbvaEditor.birdsEyeView.addChild(ei4);

		var line:LineIcon = new LineIcon(ei1,ei2);
		line.text = "は";
        this.sbvaEditor.birdsEyeView.addChildAt(line, 0); // 最背面に追加

		line = new LineIcon(ei2,ei3);
		line.text = "と";
        this.sbvaEditor.birdsEyeView.addChildAt(line, 0); // 最背面に追加

		line = new LineIcon(ei2,ei4);
		line.text = "を";
        this.sbvaEditor.birdsEyeView.addChildAt(line, 0); // 最背面に追加
        */
    }
    
    private function analyzeScenario():void {
    	trace("- start analisis...");
    	this.analyzeEntities();
    	this.analyzeProcesses();
    	this.analyzeRelations();
    	
    	trace("- change test...")
    	this.sbvaEditor.entityCollection[0].@test = "hoge";;
    	trace("- delete test...");
    	this.sbvaEditor.entityCollection.removeItemAt(0);
		trace(this.generateXML());
    }
    
    private function analyzeEntities():void {
    	trace("- analyze entities...");
		// Entityを格納するコレクションを用意します    	
		//this.sbvaEditor.entityCollection.source = new XMLList();
		this.sbvaEditor.entityCollection = new XMLListCollection();
    	var entitiesCollection:XMLListCollection = this.sbvaEditor.entityCollection;

    	// 主語（subject)または目的語(Object)を抽出します
    	for each(var subjectOrObject:XML in
    		_model.scenario.task.noun.subject
    		+ _model.scenario.task.noun.object) {

    		// すでに登録してあるエンティティかどうかチェックします（o(n)なので要検討）
			var entityRefId:String = null;
    		for each(var storedEntity:XML in entitiesCollection) {
    			if(storedEntity.toString() == subjectOrObject.toString()) {
    				entityRefId = storedEntity.@id;
    				var name:String = subjectOrObject.name();
    				storedEntity.@[name] = "yes";
       			}
      		}
      		
      		// 見つからなかった場合，新規のEntityを作成します
      		if(entityRefId == null) {
	    		// subjectまたはobjectのエンティティを作成します
    			entityRefId = this.generateId();
	    		var newEntity:XML =
    				<entity id={entityRefId} {subjectOrObject.name()}="yes">
    					{subjectOrObject.toString()}
	    		    </entity>
    			// Entityのリストに追加します
    			trace("- adding new entity:" + newEntity.toXMLString()); 
	    		entitiesCollection.addItem(newEntity);
    		}
    		
    		// 参照IDをつけ，テキストを削除します
    		subjectOrObject.@entityIDREF = entityRefId;
    		delete subjectOrObject.*;
    	}
    }
    
    private function analyzeProcesses():void {
    	trace("- analyze processes...");
    	this.sbvaEditor.processCollection = new XMLListCollection();
    	var processesCollection:XMLListCollection = this.sbvaEditor.processCollection;

		// 動詞(verb)をプロセスに追加する
		for each(var verb:XML in _model.scenario.task.verb) {
   			var processRefId:String = this.generateId();
			var process:XML =
				<process id={processRefId}>
				  {verb.toString()}
				</process>
			processesCollection.addItem(process);

    		// 参照IDをつけ，テキストを削除します
    		verb.@processIDREF = processRefId;
    		delete verb.*;
		}
    }
    
    private function analyzeRelations():void {
    	trace("- analyze relations...");
    	this.sbvaEditor.relationCollection = new XMLListCollection();
    	var relationsCollection:XMLListCollection = this.sbvaEditor.relationCollection;
    	
    	// 全ての主語と目的語について，対応する動詞要素の関係を生成します
    	for each(var subjectOrObject:XML in _model.scenario.task.noun.subject
    	 + _model.scenario.task.noun.object) {
    	 	// 関連する述語と助詞（前置詞）を取得する
    	 	var noun:XML = subjectOrObject.parent();
    	 	var task:XML = noun.parent();
			var verb:XML = task.verb[0]; // verbは１つのタスクにつき１つ
			var position:XML = new XML(); // positionはない場合もある
			if(noun.position.length() > 0) {
				position = noun.position[0];
			} else {
				noun.position = "";
				position = noun.position[0];
			}

			// 関係の要素を生成して登録する
			var relationIDREF:String = this.generateId();
			var relation:XML =
			    <relation id={relationIDREF}
			    	type={subjectOrObject.name()}
			        elementIDREF={subjectOrObject.@entityIDREF}
			        processIDREF={verb.@processIDREF}>
			        {position.toString()}
			    </relation>
			relationsCollection.addItem(relation);
			
    		// 参照IDをつけ，テキストを削除します
			position.@relationIDREF = relationIDREF;
			delete position.*;
    	}
    }
	
	public function generateXML():XML {
		var newModel:XML = <model/>;
		newModel.appendChild(_model.scenario);
		newModel.appendChild("<entities>" + this.sbvaEditor.entityCollection.toXMLString() + "</entities>");
		newModel.appendChild("<processes>" + this.sbvaEditor.processCollection.toXMLString() + "</processes>");
		newModel.appendChild("<relations>" + this.sbvaEditor.relationCollection.toXMLString() + "</relations>"); 
		return newModel;
	} 
	
	// モデルを保持するXML	
	private var _model:XML;

	public function set model(model:XML):void {
		this._model = model;
		this.analyzeScenario();
	}

   	// アプリケーションの参照用（ダウンキャスト）
   	private var _sbvaEditor:SBVAEditor; // UIComponentからダウンキャストして保存します．
   	
	public function get sbvaEditor():SBVAEditor {
		if(this._sbvaEditor == null) {
			this._sbvaEditor = super.document as SBVAEditor; 
		}
       	return this._sbvaEditor;
	}
    
    // IDの生成
   	private static var currentId:Number = 0;
   	
	private function checkId(xml:XML):void {
		if(xml.attribute("id").length() == 0) {
			xml.@id = this.generateId();
		}
	}

    private function generateId():String {
    	return (++currentId).toString();
//    	return UIDUtil.createUID();
    }
}

}